const http = require('http')
const hostname = '127.0.0.1'
const port = 3000

const server = http.createServer((req, res) => {
    res.statusCode = 200
    res.setHeader('Content-Type', 'text/plain')
    res.write(`<head><metadata charset="uft-8"></head>`)
    res.write("你好 Hello")
    res.end()
    console.log('new client connected.\t' + req.socket.localAddress + ":" + req.socket.localPort);
})

server.listen(port, hostname, () => {
    console.log(`服务器运行在 http://${hostname}:${port}/`)
})

//进程监听退出信号
process.on('SIGTERM', () => {
    server.close(() => {
        console.log('进程退出')
    })
})
// 可从其他进程向本进程发送退出信号
// process.kill(process.pid,'SIGTERM')

// 访问环境变量
//输出环境变量
console.log('---访问环境变量---')
console.log(process.env.OS)
console.log(process.env.LANG)
console.log(process.env.APPDATA)
console.log(process.env.TEMP)
console.log('---访问环境变量---')

//输出nodejs接收的参数
console.log(process.argv)
process.argv.forEach((val, index) => {
    console.log(`${index}:${val}`)
})
const args = process.argv.slice(2)

console.log(args[0])
console.log(args[1])
console.log(args[2])
//采用minimist库,处理key=value参数，需要每个参数名之前添加`--`
const args2 = require('minimist')(process.argv.slice(2))
console.log(args2['name'])
console.log(args2['age'])
console.log(args2['addr'])
//打印调用堆栈
console.trace()

//计算耗时
console.time('env')
console.log(process.env)
console.timeEnd('env')
//输出着色
console.log('\x1b[33m%s\x1b[0m', '你好')
console.log(require('chalk').red('hello')) //使用chalk库 npm install chalk

// //创建进度条
// const ProgressBar = require('progress')
// const bar = new ProgressBar(':bar', {
//     total: 10
// })
// const timer = setInterval(() => {
//     bar.tick()
//     if (bar.complete) {
//         clearInterval(timer)
//     }
// }, 100)

// //从命令行接收输入
// const readline = require('readline').createInterface({
//     input: process.stdin,
//     output: process.stdout
// })
// readline.question(`输入用户名?`, name => {
//     console.log(`用户:${name}!`)
//     readline.close()
// })
// //输入密码
const inquirer = require('inquirer')
var questions = [
  {
    type: 'input',
    name: 'name',
    message: "你叫什么名字?"
  }
]
inquirer.prompt(questions).then(answers => {
  console.log(`你好 ${answers['name']}!`)
})